// 导入数据库操作模块
const db = require('../../db/index')

const fs = require('fs')
const path = require('path')
const configFile = path.resolve(__dirname, '../../../data/authors.json')
console.log('configFile', configFile)

// 获取全部作者信息(JSON)
exports.getAuthorJSON = (req, res) => {
    try {
        const data = fs.readFileSync(configFile, 'UTF-8').toString()
        let config = JSON.parse(data)
        let arr = []
        let s = ''
        config.forEach((item, index) => {
            // if(item.Dynasty == '夏') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(28)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '商') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(29)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '周') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(30)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '秦') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(31)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '汉') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(32)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '三国') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(33)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '晋') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(34)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '南北朝') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(35)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '隋') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(36)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '唐') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(37)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '五代十国') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(38)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '辽') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(39)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '宋') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(40)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '金') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(41)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '元') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(42)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '明') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(43)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // } else if(item.Dynasty == '清') {
            //     let obj = []
            //     obj.push(`${item.Id}`)
            //     obj.push(44)
            //     obj.push(`${item.Name}`)
            //     obj.push(`${item.Desc}`)
            //     obj.push(`${item.BirthYear} - ${item.DeathYear}`)
            //     obj.push(1)
            //     arr.push(obj)
            // }
            // const insertSql = `insert into author(author_id, did, a_name, a_synopsis, a_time, a_state) values ?`
            if(index != (config.length - 1)) {
                s += `update author set a_name='${item.Name}' where author_id='${item.Id}';`
            } else {
                s += `update author set a_name='${item.Name}' where author_id='${item.Id}'`
            }
        })
        console.log('s', s)
        db.query(s, (err, insertRes) => {
            if(err) return res.operationSuccess('failure', 'ERR061', '添加作者信息失败！', err)
            return res.operationSuccess('success', '', '添加作者信息成功！', [])
        })
    } catch (error) {
        console.log('get_config.error', error)
    }
}

// 获取全部作者信息(分页查询公式：(当前页数-1) * 每页条数，每页条数))
exports.getAuthor = (req, res) => {
    const { pageNum, pageSize } = req.body
    let starNum = (pageNum-1)*pageSize
    const sql1 = `select count(distinct(a.author_id)) as total from author a, dynasty d where a.did=d.did and a.a_state=1`
    const sql2 = `select a.author_id, a.a_name, a.a_synopsis, a.a_time, d.d_name, d.did from author a, dynasty d where a.did = d.did and a.a_state=1 limit ${starNum}, ${pageSize}`
    db.query(sql1, (err1, results1) => {
        if(err1) return res.operationSuccess('failure', 'ERR060', '查找作者信息失败！', err1)
        // return res.operationSuccess('success', '', '查找作者信息成功！', results)
        db.query(sql2, (err2, results2) => {
            if(err2) return res.operationSuccess('failure', 'ERR060', '查找作者信息失败！', err2)
            return res.operationSuccess('success', '', '查找作者信息成功！', {total: results1[0].total, results2: results2})
        })
    })
}

// 获取全部作者信息并根据朝代进行分类
exports.getAuthorOrderByDynasty = (req, res) => {
    // const { pageNum, pageSize } = req.body
    // let starNum = (pageNum-1)*pageSize
    // const sql1 = `select count(distinct(a.author_id)) as total from author a, dynasty d where a.did=d.did and a.a_state=1`
    const sql = `select a.author_id, a.a_name, a.a_synopsis, a.a_time, d.d_name, d.did from author a, dynasty d where a.did = d.did and a.a_state=1`
    db.query(sql, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR060', '查找作者信息失败！', err)
        // return res.operationSuccess('success', '', '查找作者信息成功！', results)
        // const data = [/* 将数据集放在这里 */];
        // 创建一个空对象，用来存储分类后的数据
        const classifiedData = {};
        // 遍历数据集
        for (let item of results) {
            if(item.did != 45) {
                const dynasty = item.d_name; // 获取当前项的朝代名
                // 如果分类对象中没有当前朝代名的属性，则创建一个空数组
                if (!classifiedData[dynasty]) {
                    classifiedData[dynasty] = [];
                }
                // 将当前项添加到对应的朝代数组中
                classifiedData[dynasty].push(item);
            }
        }
        return res.operationSuccess('success', '', '查找作者信息成功！', classifiedData)
    })
}

// 添加作者信息
exports.addAuthor = (req, res) => {
    const { dynasty, name, synopsis, time } = req.body 
    let author_id = Date.parse(new Date())
    const sql = `insert into author(author_id, a_name, a_synopsis, a_time, did, a_state) values('${author_id}', '${name}', '${synopsis}', '${time}', ${dynasty}, 1)`
    db.query(sql, (err, results2) => { 
        if(err) return res.operationSuccess('failure', 'ERR064', '添加作者信息失败！', err)
        return res.operationSuccess('success', '', '添加作者信息成功！', [])
    })
}

// 根据朝代或名称查询作者
exports.searchAuthorByDynastyOrName = (req, res) => {
    const { searchType, searchText, pageNum, pageSize } = req.body
    // 判断用户是根据名称还是时间查询
    // D 为根据朝代查询， N 为根据姓名查询， 
    let type = ''
    searchType == 'D' ? type = 'd.d_name' : type = 'a.a_name' 
    let starNum = 0
    let sql = ''
    if(pageSize && pageNum) {
        starNum = (pageNum-1)*pageSize
        sql = `select a.author_id, a.a_name, a.a_synopsis, a.a_time, d.d_name from author a, dynasty d where a.did=d.did and ${type} like '%${searchText}%' and a.a_state=1 limit ${starNum}, ${pageSize}`
    } else {
        sql = `select a.author_id, a.a_name, a.a_synopsis, a.a_time, d.d_name from author a, dynasty d where a.did=d.did and ${type} like '%${searchText}%'`
    }
    console.log(sql)
    // 1 代表未删除  0代表删除
    db.query(sql, (err, results2) => {
        if (err) return res.operationFailed(err)
        const sql2 = `select count(distinct(a.author_id)) as total from author a, dynasty d where a.did=d.did and ${type} like '%${searchText}%'`
        db.query(sql2, (err, results1) => {
            if (err) return res.operationSuccess('failure', 'ERR060', '查找作者信息失败！', err)
            return res.operationSuccess('success', '', '查找作者信息成功！', {total: results1[0].total, results2: results2})
        })
    })
}

// 根据id删除作者信息
exports.deleteAuthorById = (req, res) => {
    // const deletSql = `delete from author where a_synopsis='null'`
    // db.query(deletSql, (err, selectRes) => {
    //     if(err) return res.operationFailed(err)
    //     return res.operationSuccess('success', '', '添加管理员账号成功！', [])
    // })
    const { author_id } = req.body
    const sql = `update author set a_state=0 where author_id in (${ author_id })`
    // const sql = `update author set a_state=1 where author_id='10385'`
    db.query(sql, (err, selectRes) => {
        if(err) return res.operationSuccess('failure', 'ERR062', '删除作者信息失败！', err)
        return res.operationSuccess('success', '', '删除作者信息成功！', [])
    })
}

// 根据id修改作者信息
exports.updateAuthorById = (req, res) => {
    const { aid, dynasty, name, synopsis, time } = req.body 
    const selectSql = `select * from author where author_id='${ aid }'`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationSuccess('failure', 'ERR060', '查询作者信息失败！', err)
        // return res.operationSuccess('success', '', '删除作者信息成功！', [])
        // let did = dynasty !== '' ? dynasty : selectRes[0].did
        // let a_name = name != '' ? name : selectRes[0].a_name
        // let a_synopsis = synopsis != '' ? synopsis : selectRes[0].a_synopsis
        // let a_time = time != '' ? time : selectRes[0].a_time
        let did = dynasty
        let a_name = name
        let a_synopsis = synopsis
        let a_time = time
        // console.log('dynasty', a_dynasty)
        // console.log('name', a_name)
        // console.log('synopsis', a_synopsis)
        // console.log('time', a_time)
        const sql = `update author set a_name='${ a_name }', a_synopsis='${ a_synopsis }', a_time='${ a_time }', did='${ did }' where author_id='${ aid }'`
        console.log(sql)
        db.query(sql, (err, selectRes) => {
            if(err) return res.operationSuccess('failure', 'ERR063', '更改作者信息失败！', err)
            return res.operationSuccess('success', '', '更改作者信息成功！', [])
        })
    })
}

// 根据id获取作者及作品信息
exports.getAuthorAndPoetryById = (req, res) => {
    const { authorId } = req.query
    // console.log(authorId)
    const sql1 = `select a.*, d.d_name from author a, dynasty d where a.author_id='${authorId}' and a.did=d.did`
    const sql2 = `select * from poetry2 where aid='${authorId}'`
    db.query(`${sql1};${sql2}`, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR065', '根据id获取作者及作品信息失败！', err)
        let obj = {author: results[0][0], poetry: results[1]}
        return res.operationSuccess('success', '', '根据id获取作者及作品信息成功！', obj)
    })
}